<?php
/***
*
* Class: OrderController //订单控制器
* Author: Jason ZHENG
* Data: 2018-06-26
*
***/
namespace App\Http\Controllers;

use App\Service\DataReturnService as DRS;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session; 
use App\Common\Base;
use App\Validator\OrderValidator;
use App\Service\OrderService;

class OrderController extends Controller
{
    /**
     * 实例化一个新的控制器实例。
     *
     * @return void
     */
    public function __construct()
    {
        
    }

    public function index()
    {
    	return "Order controller";
    }

    // 添加一个订单
    public function add(Request $request)
    {
        //传输数据验证
        $postData  = $request->post();
        $validator = Validator::make($postData, 
                                    [
                                        'token'         => 'required|string',
                                        'product_ids'   => 'required|array', 
                                        'delivery_id'   => 'required',
                                        'total_price'   => 'required',
                                    ]);
        if ($validator->fails()) {
            return DRS::returnError(1000,'验证错误！',$validator->errors());
        }
        // 用户登陆token验证
        $userInfo = Base::getUserByTokenWithPhone($postData['token']);
        if($userInfo['code'] != '666'){
            return $userInfo;
        }
        $user   = $userInfo['data'];
        // 商品是否可下订单验证
        $product_infos = OrderValidator::validateGetProducts($postData['product_ids'], $postData['delivery_id'], $user['id']);
        if($product_infos['code'] != '666'){
            return $product_infos;
        }
        // 优惠券是否可用验证
        $coupon_price = 0;
        if(isset($postData['ticket_id'])){
            $ticket = OrderValidator::validateGetTicket($postData['ticket_id'], $postData['total_price'], $user['id']);
            if($ticket['code'] != '666'){
                return $ticket;
            }else{
                $coupon_price = $ticket['data']['price'];
            }
        }
        // 不同商品根据商户归类
        $products_by_business = [];
        foreach ($product_infos['data'] as $product) 
        {   
            if($product['is_synchro'] == 1)
            {
                $sourceProduct = DB::table('product')->where( ['id'=>$product['source_product_id'], 'state' => 0] )->first();
                $products_by_business[$sourceProduct->business_id][] = $product;
            }
        }
        // 生成自商家的订单
        $ownOrder = OrderService::make_own_order($user,$postData,$product_infos['data'],$coupon_price);
        if($ownOrder['code'] != 666){
            return $ownOrder;
        }

        // 每件商品对于原商家生成相应的订单
        foreach ($products_by_business as $business_id => $products) 
        {   
            $otherOrder = OrderService::make_others_order($user,$postData,$products,$business_id, $user['business_id']);
            if($otherOrder['code'] != 666){
                return $otherOrder;
            }
        }

        return DRS::returnOk(['batchcode' => $ownOrder['data']['batchcode']]);
    }

    //获取一个订单的详情
    public function detail(Request $request)
    {
        $postData  = ['token' => $request->get('token'), 'batchcode' => $request->get('batchcode')];
        $validator = Validator::make($postData, 
                                    [
                                        'token'         => 'required|string',
                                        'batchcode'     => 'required', 
                                    ]);

        if ($validator->fails()) {
            return DRS::returnError(1000,'验证错误！',$validator->errors());
        }

        $userInfo = Base::getUserByTokenWithPhone($postData['token']);
        if($userInfo['code'] != '666'){
            return $userInfo;
        }
        $user   = $userInfo['data'];

        $order = OrderValidator::validateGetOrder($postData['batchcode'], $user['id']);
        if($order['code'] != 666)
            return $order;

        $orderInfo = OrderValidator::validateGetOrderInfo($postData['batchcode'], $user['id']);
    
        if($orderInfo['code'] != 666)
            return $orderInfo;

        $unitOrdersQuery = DB::table('unit_order')
                    ->where(['batchcode'=>$postData['batchcode'],'user_id' => $user['id']])
                    ->get()
                    ->toArray();
        $unitOrders = array_map('get_object_vars', $unitOrdersQuery);

        return DRS::returnOk(
                        array_merge(
                            ['order' => $order['data']], 
                            ['order_info' => $orderInfo['data']],
                            ['unit_orders' =>$unitOrders]
                            ));
    }

    // 取消订单
    public function remove(Request $request)
    {
        $postData  = ['token' => $request->get('token'), 'batchcode' => $request->get('batchcode')];
        $validator = Validator::make($postData, 
                                    [
                                        'token'         => 'required|string',
                                        'batchcode'     => 'required', 
                                    ]);

        if ($validator->fails()) {
            return DRS::returnError(1000,'验证错误！',$validator->errors());
        }

        $userInfo = Base::getUserByTokenWithPhone($postData['token']);
        if($userInfo['code'] != '666'){
            return $userInfo;
        }
        $user   = $userInfo['data'];

        $order = OrderValidator::validateRemoveOrder($postData['batchcode'], $user['id']);
        if($order['code'] != 666)
            return $order;

        $orderInfo = OrderValidator::validateRemoveOrderInfo($postData['batchcode'], $user['id']);
        if($orderInfo['code'] != 666)
            return $orderInfo;

        DB::beginTransaction();
        try{
            $rmOrder = OrderService::removeOrder($postData['batchcode'],$user['id']);
            if($rmOrder['code'] != 666){
                return $rmOrder;
            }
            DB::commit();
            return DRS::returnOk(true);
        }catch(\Exception $exception) {
            DB::rollBack();
            return DRS::returnError(1000,'取消订单出错，稍后再试！',$exception);
        }
    }

    // 获取订单列表
    public function list(Request $request)
    {
        $postData  = ['token' => $request->get('token')];
        $validator = Validator::make($postData, 
                                    [
                                        'token'         => 'required|string',
                                    ]);

        if ($validator->fails()) {
            return DRS::returnError(1000,'验证错误！',$validator->errors());
        }

        $userInfo = Base::getUserByTokenWithPhone($postData['token']);
        if($userInfo['code'] != '666'){
            return $userInfo;
        }
        $user   = $userInfo['data'];
        $select = ['o.id','o.batchcode', 'o.state','o.status', 'sc.value as status_value','o.total_price', 'o.total_fare',
                    'o.coupon_id', 'o.coupon_price','o.createtime','o.last_time','o.payment_status','o.pay_time','o.remark',
                    'o.shipping_code','sm.shipping_name','o.shipping_sn'];
        $allOrdersQuery = DB::table('orders as o')
                        ->leftJoin('sales_condition as sc', 'sc.id', '=', 'o.status')
                        ->leftJoin('shipping_mode as sm', 'sm.id', '=', 'o.shipping_code')
                        ->where(['o.user_id' => $user['id'], 'o.state' => 0])
                        ->select($select)
                        ->orderBy('o.last_time','desc')
                        ->get()
                        ->toArray();
        $allOrders = array_map('get_object_vars', $allOrdersQuery);

        $ordersToPay = [];
        $ordersToDeliver = [];
        $ordersToReceive = [];
        $ordersDone = [];
        foreach ($allOrders as $key => $order) {
            $select = ['oi.batchcode','oi.product_id','oi.coupon_id','oi.status','sc.value as status_value','oi.price','oi.last_time',
                        'oi.payment_status','oi.createtime','oi.remark','p.id as product_id','p.state as product_state','p.is_onsale',
                        'p.category_id','p.type_id','p.brand_id','p.systematics_id','p.is_new','p.is_hot','p.pic_url','p.product_sn',
                        'p.product_name','p.full_name','p.synopsis','p.cost_price'];
            $allOrdersInfoQuery = DB::table('orders_info as oi')
                                ->leftJoin('sales_condition as sc', 'sc.id', '=', 'oi.status')
                                ->leftJoin('product as p','p.id','=','oi.product_id')
                                ->where(['oi.batchcode' => $order['batchcode'],'p.state' =>0,'p.is_onsale' => 1])
                                ->orderBy('oi.createtime','desc')
                                ->select($select)
                                ->get()
                                ->toArray();
            $allOrdersInfo = array_map('get_object_vars', $allOrdersInfoQuery);
            $allOrders[$key]['productsInfo'] = $allOrdersInfo;

            if($order['status'] == 1){
                $ordersToPay [] = $allOrders[$key];
            }elseif($order['status'] == 2){
                $ordersToDeliver [] = $allOrders[$key];
            }elseif($order['status'] == 3){
                $ordersToReceive [] = $allOrders[$key];
            }elseif($order['status'] == 6){
                $ordersDone [] = $allOrders[$key];
            }

        }

        return DRS::returnOk([
                        'allOrders'         => $allOrders, 
                        'ordersToPay'       => $ordersToPay, 
                        'ordersToDeliver'   => $ordersToDeliver,
                        'ordersToReceive'   => $ordersToReceive,
                        'ordersDone'        => $ordersDone
                        ]);
    }

    // 获取订单统计情况
    public function stats(Request $request)
    {
        $postData  = ['token' => $request->get('token')];
        $validator = Validator::make($postData, 
                                    [
                                        'token'         => 'required|string',
                                    ]);

        if ($validator->fails()) {
            return DRS::returnError(1000,'验证错误！',$validator->errors());
        }

        $userInfo = Base::getUserByToken($postData['token']);
        if($userInfo['code'] != '666'){
            return $userInfo;
        }
        $user   = $userInfo['data'];

        $allOrdersQuery = DB::table('orders')->where(['user_id' => $user['id'], 'state' => 0])->get()->toArray();
        $allOrders = array_map('get_object_vars', $allOrdersQuery);

        $ordersToPay = [];
        $ordersToDeliver = [];
        $ordersToReceive = [];
        $ordersDone = [];
        foreach ($allOrders as $key => $order) 
        {
            if($order['status'] == 1){
                $ordersToPay [] = $allOrders[$key];
            }elseif($order['status'] == 2){
                $ordersToDeliver[] = $allOrders[$key];
            }elseif($order['status'] == 3){
                $ordersToReceive [] = $allOrders[$key];
            }elseif($order['status'] == 6){
                $ordersDone [] = $allOrders[$key];
            }

        }

        return DRS::returnOk([
                        'allOrdersCount'         => count($allOrders), 
                        'ordersToPayCount'       => count($ordersToPay), 
                        'ordersToDeliverCount'   => count($ordersToDeliver),
                        'ordersToReceiveCount'   => count($ordersToReceive),
                        'ordersDoneCount'        => count($ordersDone)
                        ]);
    }

    //订单确认收货
    public function confirm(Request $request)
    {
        $postData  = $request->post();
        $validator = Validator::make($postData, 
                                    [
                                        'token'         => 'required|string',
                                        'batchcode'     => 'required',
                                    ],
                                    [
                                        'token.required'        => 'token获取失败',
                                        'batchcode.required'    => '订单号获取失败'
                                    ]);


        if ($validator->fails()) {
            return DRS::returnError(1000,'验证错误！',$validator->errors()->first());
        }

        $userInfo = Base::getUserByTokenWithPhone($postData['token']);
        if($userInfo['code'] != '666'){
            return $userInfo;
        }
        $user   = $userInfo['data'];

        $order = OrderValidator::validateConfirmOrder($postData['batchcode'], $user['id']);
        if($order['code'] != 666)
            return $order;

        $orderInfo = OrderValidator::validateConfirmOrderInfo($postData['batchcode'], $user['id']);
        if($orderInfo['code'] != 666)
            return $orderInfo;

        //DB::beginTransaction();
        try{

            $orderConfirmed = OrderService::confirmOrder($postData['batchcode'], $user['id']);
            if($orderConfirmed['code'] != 666){
                return $orderConfirmed;
            }
            
            //DB::commit();
            return DRS::returnOk(true,'已确认收货');
        }catch(\Exception $exception) {
            //DB::rollBack();
            return DRS::returnError(1000,'订单确认收货出错，稍后再试！',$exception);
        }
    }

}